// 键盘快捷键管理Hook
// 实现标签页快捷键切换功能，支持Ctrl+Tab、Ctrl+1-9等快捷键操作

import { useEffect, useCallback, useRef } from 'react';
import { useTabStore } from '../stores/tabStore';

// 快捷键配置接口
export interface KeyboardShortcutConfig {
  enabled: boolean;
  shortcuts: {
    // 标签页导航
    nextTab: string;           // 下一个标签页
    previousTab: string;       // 上一个标签页
    recentTab: string;         // 最近访问的标签页
    firstTab: string;          // 第一个标签页
    lastTab: string;           // 最后一个标签页
    
    // 标签页操作
    closeTab: string;          // 关闭当前标签页
    closeOtherTabs: string;    // 关闭其他标签页
    closeAllTabs: string;      // 关闭所有标签页
    reopenClosedTab: string;   // 重新打开已关闭的标签页
    newTab: string;            // 新建标签页
    
    // 文件操作
    saveTab: string;           // 保存当前标签页
    saveAllTabs: string;       // 保存所有标签页
    
    // 数字键切换 (Ctrl+1-9)
    tabByIndex: string[];      // 按索引切换标签页
  };
}

// 默认快捷键配置
const DEFAULT_SHORTCUTS: KeyboardShortcutConfig = {
  enabled: true,
  shortcuts: {
    nextTab: 'Ctrl+Tab',
    previousTab: 'Ctrl+Shift+Tab',
    recentTab: 'Ctrl+`',
    firstTab: 'Ctrl+Home',
    lastTab: 'Ctrl+End',
    
    closeTab: 'Ctrl+W',
    closeOtherTabs: 'Ctrl+Shift+W',
    closeAllTabs: 'Ctrl+Alt+W',
    reopenClosedTab: 'Ctrl+Shift+T',
    newTab: 'Ctrl+T',
    
    saveTab: 'Ctrl+S',
    saveAllTabs: 'Ctrl+Shift+S',
    
    tabByIndex: [
      'Ctrl+1', 'Ctrl+2', 'Ctrl+3', 'Ctrl+4', 'Ctrl+5',
      'Ctrl+6', 'Ctrl+7', 'Ctrl+8', 'Ctrl+9'
    ],
  },
};

// 快捷键Hook选项
export interface UseKeyboardShortcutsOptions {
  config?: Partial<KeyboardShortcutConfig>;
  onNewTab?: () => void;
  onSaveTab?: (tabId: string) => void;
  onSaveAllTabs?: () => void;
}

// 解析快捷键字符串
const parseShortcut = (shortcut: string) => {
  const parts = shortcut.toLowerCase().split('+');
  return {
    ctrl: parts.includes('ctrl'),
    shift: parts.includes('shift'),
    alt: parts.includes('alt'),
    meta: parts.includes('meta') || parts.includes('cmd'),
    key: parts[parts.length - 1],
  };
};

// 检查快捷键是否匹配
const matchesShortcut = (event: KeyboardEvent, shortcut: string): boolean => {
  const parsed = parseShortcut(shortcut);
  const eventKey = event.key.toLowerCase();
  
  // 特殊键映射
  const keyMap: Record<string, string> = {
    'tab': 'tab',
    '`': '`',
    'home': 'home',
    'end': 'end',
    'escape': 'escape',
  };
  
  const normalizedKey = keyMap[parsed.key] || parsed.key;
  const normalizedEventKey = keyMap[eventKey] || eventKey;
  
  return (
    event.ctrlKey === parsed.ctrl &&
    event.shiftKey === parsed.shift &&
    event.altKey === parsed.alt &&
    event.metaKey === parsed.meta &&
    normalizedEventKey === normalizedKey
  );
};

// 键盘快捷键Hook
export const useKeyboardShortcuts = (options: UseKeyboardShortcutsOptions = {}) => {
  const { config = {}, onNewTab, onSaveTab, onSaveAllTabs } = options;
  
  const shortcuts = { ...DEFAULT_SHORTCUTS, ...config };
  const isHandlingRef = useRef(false);
  
  const {
    tabs,
    tabOrder,
    activeTabId,
    activateNextTab,
    activatePreviousTab,
    activateRecentTab,
    activateTabByIndex,
    closeTab,
    closeOtherTabs,
    closeAllTabs,
    reopenClosedTab,
    saveTab,
    saveAllTabs,
    getActiveTab,
  } = useTabStore();

  // 处理快捷键事件
  const handleKeyDown = useCallback((event: KeyboardEvent) => {
    if (!shortcuts.enabled || isHandlingRef.current) return;
    
    // 如果焦点在输入框中，某些快捷键不应该触发
    const activeElement = document.activeElement;
    const isInputFocused = activeElement && (
      activeElement.tagName === 'INPUT' ||
      activeElement.tagName === 'TEXTAREA' ||
      (activeElement as HTMLElement).contentEditable === 'true'
    );

    try {
      isHandlingRef.current = true;
      
      // 标签页导航快捷键
      if (matchesShortcut(event, shortcuts.shortcuts.nextTab)) {
        event.preventDefault();
        activateNextTab();
        return;
      }
      
      if (matchesShortcut(event, shortcuts.shortcuts.previousTab)) {
        event.preventDefault();
        activatePreviousTab();
        return;
      }
      
      if (matchesShortcut(event, shortcuts.shortcuts.recentTab)) {
        event.preventDefault();
        activateRecentTab();
        return;
      }
      
      if (matchesShortcut(event, shortcuts.shortcuts.firstTab)) {
        event.preventDefault();
        if (tabOrder.length > 0) {
          activateTabByIndex(0);
        }
        return;
      }
      
      if (matchesShortcut(event, shortcuts.shortcuts.lastTab)) {
        event.preventDefault();
        if (tabOrder.length > 0) {
          activateTabByIndex(tabOrder.length - 1);
        }
        return;
      }

      // 数字键切换标签页 (Ctrl+1-9)
      for (let i = 0; i < shortcuts.shortcuts.tabByIndex.length; i++) {
        if (matchesShortcut(event, shortcuts.shortcuts.tabByIndex[i])) {
          event.preventDefault();
          if (i < tabOrder.length) {
            activateTabByIndex(i);
          }
          return;
        }
      }

      // 标签页操作快捷键（不在输入框中时才触发）
      if (!isInputFocused) {
        if (matchesShortcut(event, shortcuts.shortcuts.closeTab)) {
          event.preventDefault();
          if (activeTabId) {
            closeTab(activeTabId);
          }
          return;
        }
        
        if (matchesShortcut(event, shortcuts.shortcuts.closeOtherTabs)) {
          event.preventDefault();
          if (activeTabId) {
            closeOtherTabs(activeTabId);
          }
          return;
        }
        
        if (matchesShortcut(event, shortcuts.shortcuts.closeAllTabs)) {
          event.preventDefault();
          closeAllTabs();
          return;
        }
        
        if (matchesShortcut(event, shortcuts.shortcuts.reopenClosedTab)) {
          event.preventDefault();
          reopenClosedTab();
          return;
        }
        
        if (matchesShortcut(event, shortcuts.shortcuts.newTab)) {
          event.preventDefault();
          onNewTab?.();
          return;
        }
        
        if (matchesShortcut(event, shortcuts.shortcuts.saveTab)) {
          event.preventDefault();
          if (activeTabId) {
            saveTab(activeTabId);
            onSaveTab?.(activeTabId);
          }
          return;
        }
        
        if (matchesShortcut(event, shortcuts.shortcuts.saveAllTabs)) {
          event.preventDefault();
          saveAllTabs();
          onSaveAllTabs?.();
          return;
        }
      }
    } finally {
      isHandlingRef.current = false;
    }
  }, [
    shortcuts,
    tabOrder,
    activeTabId,
    activateNextTab,
    activatePreviousTab,
    activateRecentTab,
    activateTabByIndex,
    closeTab,
    closeOtherTabs,
    closeAllTabs,
    reopenClosedTab,
    saveTab,
    saveAllTabs,
    onNewTab,
    onSaveTab,
    onSaveAllTabs,
  ]);

  // 注册全局键盘事件监听器
  useEffect(() => {
    if (shortcuts.enabled) {
      document.addEventListener('keydown', handleKeyDown);
      return () => {
        document.removeEventListener('keydown', handleKeyDown);
      };
    }
  }, [handleKeyDown, shortcuts.enabled]);

  // 获取快捷键描述
  const getShortcutDescription = useCallback((action: keyof typeof shortcuts.shortcuts): string => {
    const shortcut = shortcuts.shortcuts[action];
    if (Array.isArray(shortcut)) {
      return shortcut.join(', ');
    }
    return shortcut as string;
  }, [shortcuts]);

  // 获取所有快捷键列表
  const getAllShortcuts = useCallback(() => {
    return Object.entries(shortcuts.shortcuts).map(([action, shortcut]) => ({
      action,
      shortcut: Array.isArray(shortcut) ? shortcut.join(', ') : shortcut,
      description: getActionDescription(action),
    }));
  }, [shortcuts]);

  return {
    shortcuts,
    getShortcutDescription,
    getAllShortcuts,
  };
};

// 获取操作描述
const getActionDescription = (action: string): string => {
  const descriptions: Record<string, string> = {
    nextTab: '下一个标签页',
    previousTab: '上一个标签页',
    recentTab: '最近访问的标签页',
    firstTab: '第一个标签页',
    lastTab: '最后一个标签页',
    closeTab: '关闭当前标签页',
    closeOtherTabs: '关闭其他标签页',
    closeAllTabs: '关闭所有标签页',
    reopenClosedTab: '重新打开已关闭的标签页',
    newTab: '新建标签页',
    saveTab: '保存当前标签页',
    saveAllTabs: '保存所有标签页',
    tabByIndex: '按索引切换标签页',
  };
  
  return descriptions[action] || action;
};
